package com.ethink.platform.manager;

import cn.hutool.core.bean.BeanUtil;
import com.ethink.warehouse.api.MateInventoryFacade;
import com.ethink.warehouse.api.info.MateInventoryDetailInfo;
import com.ethink.warehouse.api.model.LogisticsTransferOrderExcelModel;
import com.ethink.warehouse.api.model.LogisticsTransferOrderReturnExcelModel;
import com.ethink.warehouse.api.request.MateInventoryQueryKeyInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 辉辉 2023/2/22 9:48
 */
@Component
public class LogisticsTransferOrderManager {

    @Autowired
    private ExcelImportManager excelImportManager;

    @Resource
    private MateInventoryFacade mateInventoryFacade;

    public List<LogisticsTransferOrderReturnExcelModel> logisticsTransferOrderImport(MultipartFile file, String subWarehouseCode) {
        List<LogisticsTransferOrderExcelModel> logisticsTransferOrderExcelModels = excelImportManager.transferClass(file, LogisticsTransferOrderExcelModel.class);
        List<MateInventoryQueryKeyInfo> keyList = new ArrayList<>();
        logisticsTransferOrderExcelModels.forEach(item -> {
            MateInventoryQueryKeyInfo keyInfo = new MateInventoryQueryKeyInfo();
            keyInfo.setMateSku(item.getMateSku());
            keyInfo.setInventoryType(item.getInventoryType());
            keyInfo.setPurchaseCode(item.getPurchaseCode());
            keyInfo.setSubWarehouseCode(subWarehouseCode);
            keyInfo.setSaleSubChannel(item.getSaleSubChannel());
            keyList.add(keyInfo);
        });
        List<MateInventoryDetailInfo> inventoryDetailInfos = mateInventoryFacade.listMateInventoryByKeyList(keyList);
        List<LogisticsTransferOrderReturnExcelModel> res = new ArrayList<>();
        inventoryDetailInfos.forEach(item -> {
            // 调拨数量
            logisticsTransferOrderExcelModels.forEach(inData -> {
                if (inData.getMateSku().equals(item.getMateSku())) {
                    LogisticsTransferOrderReturnExcelModel resData = BeanUtil.copyProperties(item, LogisticsTransferOrderReturnExcelModel.class);
                    resData.setInventoryType(item.getSumQty());
                    resData.setQty(inData.getQty());
                    resData.setInventoryType(item.getInventoryType());
                    if (item.getAvailableQty() < inData.getQty()) {
                        resData.setQty(item.getAvailableQty());
                    }
                    resData.setMateInventoryId(item.getId());
                    res.add(resData);
                }
            });
        });
        return res;
    }
}
